package org.lld.im.service.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lld.im.codec.pack.user.UserModifyPack;
import org.lld.im.common.ResponseVO;
import org.lld.im.common.config.AppConfig;
import org.lld.im.common.constant.Constants;
import org.lld.im.common.enums.DelFlagEnum;
import org.lld.im.common.enums.UserErrorCode;
import org.lld.im.common.enums.command.UserEventCommand;
import org.lld.im.service.group.service.ImGroupService;
import org.lld.im.service.user.dao.ImUserDataEntity;
import org.lld.im.service.user.dao.mapper.ImUserDataMapper;
import org.lld.im.service.user.model.req.*;
import org.lld.im.service.user.model.resp.GetUserInfoResp;
import org.lld.im.service.user.model.resp.ImportUserResp;
import org.lld.im.service.user.service.UserService;
import org.lld.im.service.utils.CallbackService;
import org.lld.im.service.utils.MessageProducer;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: LunBoWang
 * @description: TODO
 * @date: 2025/3/13 下午7:10
 * @version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    ImUserDataMapper imUserDataMapper;
    @Resource
    AppConfig appConfig;
    @Resource
    CallbackService callbackService;
    @Resource
    private MessageProducer messageProducer;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    ImGroupService imGroupService;

    // 导入用户
    @Override
    public ResponseVO importUser(ImportUserReq req) {
        //如果批量导入的数据过多会提示报错，限制导入用户数量为一百
        if (req.getUserData().size() > 100) {
            return ResponseVO.errorResponse(UserErrorCode.IMPORT_SIZE_BEYOND);
        }
        List<String> successId = new ArrayList<>();
        List<String> errorId = new ArrayList<>();
        req.getUserData().forEach(e -> {
                    try {
                        //将一个APPId的数据导入到一个APPId的数据库中
                        e.setAppId(req.getAppId());
                        int insert = imUserDataMapper.insert(e);
                        if (insert == 1) {
                            successId.add(e.getUserId());
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        errorId.add(e.getUserId());
                    }
                }
        );
        ImportUserResp resp = new ImportUserResp();
        resp.setSuccessId(successId);
        resp.setErrorId(errorId);
        return ResponseVO.successResponse(resp);
    }

    // 获取多个用户信息
    @Override
    public ResponseVO<GetUserInfoResp> getUserInfo(GetUserInfoReq req) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("app_id", req.getAppId());
        wrapper.in("user_id", req.getUserIds());
        wrapper.eq("del_flag", DelFlagEnum.NORMAL.getCode());
        List<ImUserDataEntity> list = imUserDataMapper.selectList(wrapper);
        HashMap<String, ImUserDataEntity> map = new HashMap<>();
        list.forEach(e -> {
            map.put(e.getUserId(), e);
        });
        List<String> failUser = new ArrayList<>();
        List<String> successUser = new ArrayList<>();
        req.getUserIds().forEach(e -> {
            if (!map.containsKey(e)) {
                failUser.add(e);
            } else {
                successUser.add(e);
            }
        });
        if (successUser.size() == 0) {
            return ResponseVO.errorResponse(UserErrorCode.USERS_IS_NOT_EXIST);
        }
        return ResponseVO.successResponse(successUser);
    }

    // 获取单个用户信息
    @Override
    public ResponseVO<ImUserDataEntity> getSingleUserInfo(String userId, Integer appId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("app_id", appId);
        wrapper.eq("user_id", userId);
        wrapper.eq("del_flag", DelFlagEnum.NORMAL.getCode());
        ImUserDataEntity entity = imUserDataMapper.selectOne(wrapper);
        if (entity != null) {
            return ResponseVO.successResponse(entity);
        }
        return ResponseVO.errorResponse(UserErrorCode.USER_IS_NOT_EXIST);
    }

    // 删除用户
    @Override
    public ResponseVO<Integer> deleteUser(DeleteUserReq req) {
        ImUserDataEntity entity = new ImUserDataEntity();
        entity.setDelFlag(DelFlagEnum.DELETE.getCode());
        List<String> successId = new ArrayList<>();
        List<String> errorId = new ArrayList<>();
        req.getUserId().forEach(e -> {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("app_id", req.getAppId());
            wrapper.eq("user_id", e);
            wrapper.eq("del_flag", DelFlagEnum.NORMAL.getCode());
            int update;
            try {
                update = imUserDataMapper.update(entity, wrapper);
                if (update > 0) {
                    successId.add(e);
                } else {
                    errorId.add(e);
                }
            } catch (Exception ex) {
                errorId.add(e);
                ex.printStackTrace();
            }
        });
        ImportUserResp resp = new ImportUserResp();
        resp.setSuccessId(successId);
        resp.setErrorId(errorId);
        return ResponseVO.successResponse(resp);
    }

    // 修改用户信息
    @Transactional
    @Override
    public ResponseVO modifyUserInfo(ModifyUserInfoReq req) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("app_id", req.getAppId());
        wrapper.eq("user_id", req.getUserId());
        wrapper.eq("del_flag", DelFlagEnum.NORMAL.getCode());
        ImUserDataEntity entity = imUserDataMapper.selectOne(wrapper);
        //用户不存在
        if (entity == null) {
            return ResponseVO.errorResponse(UserErrorCode.USER_IS_NOT_EXIST);
        }
        ImUserDataEntity updateEntity = new ImUserDataEntity();
        //复制req对象地属性到updateEntity对象中
        BeanUtils.copyProperties(req, updateEntity);
        int update = imUserDataMapper.update(updateEntity, wrapper);
        if (update == 1) {
            //通知
            UserModifyPack pack = new UserModifyPack();
            BeanUtils.copyProperties(req, pack);
            messageProducer.sendToUser(req.getUserId(),req.getClientType(),req.getImei(),
                    UserEventCommand.USER_MODIFY,pack,req.getAppId());
            //回调
            if (appConfig.isModifyUserAfterCallback()) {
                callbackService.callback(req.getAppId(),
                        Constants.CallbackCommand.ModifyUserAfter, JSONObject.toJSONString(req));
            }
            return ResponseVO.successResponse();
        }
        //修改失败
        return ResponseVO.errorResponse(UserErrorCode.MODIFY_USER_ERROR);
    }

    @Override
    public ResponseVO login(LoginReq req) {
        return ResponseVO.successResponse();
    }

    @Override
    public ResponseVO getUserSequence(GetUserSequenceReq req) {
        Map<Object,Object> map = redisTemplate.opsForHash().entries(req.getAppId() + ":" + Constants.RedisConstants.SeqPrefix + ":" + req.getUserId());
        Long groupSeq = imGroupService.getUserGroupMaxSeq(req.getUserId(), req.getAppId());
        map.put(Constants.SeqConstants.Group,groupSeq);
        return ResponseVO.successResponse(map);
    }


}
